<template>
  <el-row class="warp">
    <el-col :span="24" class="warp-breadcrum">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }"><b>首页</b></el-breadcrumb-item>
        <el-breadcrumb-item>游戏管理</el-breadcrumb-item>
        <el-breadcrumb-item>游戏列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>

    <el-col :span="24" class="warp-main" v-loading="loading" element-loading-text="拼命加载中">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="filters">
          <el-form-item>
            <el-input v-model="filters.name" placeholder="游戏名" @keyup.enter.native="handleSearch"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-on:click="handleSearch">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="showAddDialog">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <!--========================================================列表============================================================-->
      <el-table :data="games" highlight-current-row @selection-change="selsChange"
                style="width: 100%;">
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        <el-table-column type="index" width="100" align="center"></el-table-column>
        <el-table-column prop="title" label="游戏标题" width="300" sortable align="center"></el-table-column>
        <el-table-column prop="etitle" label="英文标题" width="300" sortable align="center"></el-table-column>
        <el-table-column prop="time" label="发行日期" align="center" width="300" :formatter="formatterDate" sortable></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" @click="showDetailDialog(scope.$index,scope.row)">查看</el-button>
            <el-button type="primary" @click="showEditDialog(scope.$index,scope.row)" size="small">编辑</el-button>
            <el-button type="danger" @click="delGame(scope.$index,scope.row)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!-- ============================================================================================================================ -->


<!--  -----------------------------------------------------工具条------------------------------------------------------------------ -->
      <el-col :span="24" class="toolbar">
        <!-- <el-button type="danger" @click="batchDeleteBook" :disabled="this.sels.length===0">批量删除</el-button> -->
        <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="8" :total="total"
                       style="float:right;">
        </el-pagination>
      </el-col>
<!-- --------------------------------------------------------------------------------------------------------------------------- -->

<!-- =========================================================查看=============================================================== -->
      <el-dialog title="查看" :visible.sync ="detailsFormVisible" :close-on-click-modal="false">
        <el-form :model="detailsForm" label-width="100px" ref="detailsForm">
          <el-form-item label="游戏名" prop="title">
            <el-input v-model="detailsForm.title" auto-complete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="英文名" prop="etitle">
            <el-input v-model="detailsForm.etitle" auto-complete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="缩略图" prop="image">
            <el-image
                  style="width: 100px; height: 100px"
                  :src="url"
                  :fit="fit"></el-image>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="detailsForm.t_id" disabled placeholder="请选择类型">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发行时间">
            <el-date-picker type="date" placeholder="选择日期" v-model="detailsForm.time" disabled></el-date-picker>
          </el-form-item>
          <el-form-item label="售价" prop="price">
            <el-input v-model="detailsForm.price" auto-complete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="简介" prop="brief">
            <el-input type="input" v-model="detailsForm.brief" disabled></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input type="textarea" v-model="detailsForm.content" disabled></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="detailsFormVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click.native="editSubmit">提交</el-button> -->
        </div>
      </el-dialog>
<!-- =========================================================================================================================== -->

<!-- =========================================================编辑=============================================================== -->
      <el-dialog title="编辑" :visible.sync ="editFormVisible" :close-on-click-modal="false">
        <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
          <el-form-item label="游戏名" prop="title">
            <el-input v-model="editForm.title" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="英文名" prop="etitle">
            <el-input v-model="editForm.etitle" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="editForm.t_id" placeholder="请选择类型">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发行时间">
            <el-date-picker type="date" placeholder="选择日期" v-model="editForm.time"></el-date-picker>
          </el-form-item>
          <el-form-item label="售价" prop="price">
            <el-input v-model="editForm.price" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="简介" prop="brief">
            <el-input type="input" v-model="editForm.brief"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input type="textarea" v-model="editForm.content"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click.native="editSubmit">提交</el-button>
        </div>
      </el-dialog>
<!-- =========================================================================================================================== -->


<!-- ================================================================新增界面==================================================== -->
      <el-dialog title="新增" :visible.sync ="addFormVisible" :close-on-click-modal="false">
        <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm" >
          <el-form-item label="游戏名" prop="title">
            <el-input v-model="addForm.title" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="英文名" prop="etitle">
            <el-input v-model="addForm.etitle" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="缩略图" ref="uploadElement" prop="image">
            <el-upload
               class="upload-demo"
               accept="image/jpeg,image/jpg,image/png"
               action="http://10.2.24.239:9087/game/addGame"
               ref = "upload"
               :auto-upload="false"
               :on-preview="handlePreview"
               :on-change="handleChange"
               :data="addForm">
                <el-button type="success" size="small">选择文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="发行日期" prop="time">
            <el-date-picker type="date" placeholder="选择日期" v-model="addForm.time"></el-date-picker>
          </el-form-item>
          <el-form-item label="售价" prop="price">
            <el-input  v-model="addForm.price" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="addForm.t_id" placeholder="请选择类型">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="简介" prop="brief">
            <el-input  v-model="addForm.brief" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input el-input type="textarea" v-model="addForm.content" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <el-button type="primary"  @click="submitUpload('addForm')" :loading="addLoading">提交</el-button>
        </div>
      </el-dialog>
<!-- ============================================================================================================================ -->
    </el-col>
  </el-row>
</template>
<script>
  import util from '../../common/util'
  import API from '../../api/api_game';

  export default{
    data(){
      return {
        filters: {
          name: ''
        },
        fit: 'fill',
        url: '',
        options: [],
        games: [],
        total: 0,
        page: 1,
        limit: 10,
        loading: false,
        sels: [], //列表选中列

        //查看相关数据
        detailsFormVisible: false,
        detailsForm: {
          title: '',
          etitle: '',
          image: '',
          // time: '',
          price: '',
          //type: '',
          t_id: '',
          brief: '',
          content: '',
        },

        //编辑相关数据
        editFormVisible: false,//编辑界面是否显示
        editFormRules: {
          title: [
            {required: true, message: '请输入游戏名', trigger: 'blur'}
          ],
          etitle: [
            {required: true, message: '请输入英文名', trigger: 'blur'}
          ],
          // image: [
          //   {required: true, message: '请插入缩略图', trigger: 'blur'}
          // ],
          video: [
            {required: true, message: '请插入动画', trigger: 'blur'}
          ],
          img_1: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          img_2: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          img_3: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          img_4: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '请输入售价', trigger: 'blur'}
          ],
          // type: [
          //   {required: true, message: '请输入类型', trigger: 'blur'}
          // ],
          brief: [
            {required: true, message: '请输入简介', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '请输入内容', trigger: 'blur'}
          ],
        },
        editForm: {
          title: '',
          etitle: '',
          video: '',
          img_1: '',
          img_2: '',
          img_3: '',
          img_4: '',
          // time: '',
          price: '',
          //type: '',
          t_id: '',
          brief: '',
          content: '',
        },

        //新增相关数据
        addFormVisible: false,//新增界面是否显示
        addLoading: false,
        addFormRules: {
          title: [
            {required: true, message: '请输入游戏名', trigger: 'blur'}
          ],
          etitle: [
            {required: true, message: '请输入英文名', trigger: 'blur'}
          ],
          // image: [
          //   {required: true, message: '请插入缩略图', trigger: 'blur'}
          // ],
          video: [
            {required: true, message: '请插入动画', trigger: 'blur'}
          ],
          img_1: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          img_2: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          img_3: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          img_4: [
            {required: true, message: '请插入图片', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '请输入售价', trigger: 'blur'}
          ],
          // type: [
          //   {required: true, message: '请输入类型', trigger: 'blur'}
          // ],
          brief: [
            {required: true, message: '请输入简介', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '请输入内容', trigger: 'blur'}
          ],
        },
        addForm: {
          title: '',
          etitle: '',
          video: '',
          img_1: '',
          img_2: '',
          img_3: '',
          img_4: '',
          // time: '',
          price: '',
          //type: '',
          t_id: '',
          brief: '',
          content: '',
        }
      }
    },
    methods: {

      formatterDate : function(row,column)
      {
        return util.formatDate.format(new Date(row.time),'yyyy-MM-dd');
      },

      handlePreview(file)
      {
        console.log(file);
      },
      handleChange(file)
      {
        console.log(file);
      },

      handleCurrentChange(val) {
        this.page = val;
        this.search();
      },
      handleSearch(){
        this.total = 0;
        this.page = 1;
        this.search();
      },
      search(){
        let that = this;
        let params = {
          page: that.page,
          limit: 8,
          title: that.filters.name,
          type: '',
        };

        that.loading = true;
        API.findList(params).then(function (result) {
          that.loading = false;
          console.log(result);
          if (result.code === 200) {
            that.total = result.total;
            that.games = result.data;
          }
        }, function (err) {
          that.loading = false;
          that.$message.error({showClose: true, message: err.toString(), duration: 2000});
        }).catch(function (error) {
          that.loading = false;
          console.log(error);
          that.$message.error({showClose: true, message: '请求出现异常', duration: 2000});
        });

        //获取类型列表
        API.findTypeList().then(function(result){
          that.loading = false;
          console.log(result);
          if(result.code === 200)
          {
            that.options = result.data;
          }
        });

      },
      selsChange: function (sels) {
        this.sels = sels;
      },

      //删除
      delGame: function (index, row) {
        let that = this;
        this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'}).then(() => {
          that.loading = true;
          API.remove(row.id).then(function (result) {
            that.loading = false;
            if (result.code === 200) {
              that.$message.success({showClose: true, message: '删除成功', duration: 1500});
              that.search();
            }
          }, function (err) {
            that.loading = false;
            that.$message.error({showClose: true, message: err.toString(), duration: 2000});
          }).catch(function (error) {
            that.loading = false;
            console.log(error);
            that.$message.error({showClose: true, message: '请求出现异常', duration: 2000});
          });
        }).catch(() => {
        });
      },


      //显示查看页面
      showDetailDialog: function (index,row)
      {
        let that = this;
        this.detailsFormVisible = true;
        this.detailsForm = Object.assign({},row);
        let para = Object.assign({},this.detailsForm);
        API.findById(para.id).then(function (result){
          console.log(result);
          if(result.code === 200)
          {
            that.url = result.data.image;
          }
          else
          {
            that.$message.error({showClose: true,message: '图片路径请求出错',duration: 2000});
          }
        });
      },

      //显示编辑界面
      showEditDialog: function (index, row) {
        this.editFormVisible = true;
        this.editForm = Object.assign({}, row);
      },

      //编辑
      editSubmit: function () {
        let that = this;
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.loading = true;
            let para = new FormData();
            para.append("title",this.editForm.title);
            para.append("etitle",this.editForm.etitle);
            para.append("price",this.editForm.price);
            para.append("time",this.editForm.time)
            para.append("t_id",this.editForm.t_id);
            para.append("brief",this.editForm.brief);
            para.append("content",this.editForm.content);
            let para1 = Object.assign({}, this.editForm);
            //para.publishAt = (!para.publishAt || para.publishAt == '') ? '' : util.formatDate.format(new Date(para.publishAt), 'yyyy-MM-dd');
            API.update(para1.id, para).then(function (result) {
              that.loading = false;
              if (result.code  === 200) {
                console.log(result);
                that.$message.success({showClose: true, message: '修改成功', duration: 2000});
                that.$refs['editForm'].resetFields();
                that.editFormVisible = false;
                that.search();
              } else {
                that.$message.error({showClose: true, message: '修改失败', duration: 2000});
              }
            }, function (err) {
              that.loading = false;
              that.$message.error({showClose: true, message: err.toString(), duration: 2000});
            }).catch(function (error) {
              that.loading = false;
              console.log(error);
              that.$message.error({showClose: true, message: '请求出现异常', duration: 2000});
            });
          }
        });
      },
      showAddDialog: function () {
        this.addFormVisible = true;
        this.addForm = {
          name: '',
          author: '',
          publishAt: '',
          description: ''
        };
      },
      // //新增
      // addSubmit: function () {
      //   let that = this;
      //   this.$refs.addForm.validate((valid) => {
      //     if (valid) {
      //       that.loading = true;
      //       let para = new FormData();
      //       //para.append("image",this.addForm.image);
      //       para.append("title",this.addForm.title);
      //       para.append("etitle",this.addForm.etitle);
      //       para.append("price",this.addForm.price);
      //       para.append("t_id",this.addForm.t_id);
      //       para.append("brief",this.addForm.brief);
      //       para.append("content",this.addForm.content);

      //       // para.publishAt = (!para.publishAt || para.publishAt === '') ? '' : util.formatDate.format(new Date(para.publishAt), 'yyyy-MM-dd');
      //       API.add(para).then(function (result) {
      //         that.loading = false;
      //         if (result.code === 200) {
      //           that.$message.success({showClose: true, message: '新增成功', duration: 2000});
      //           that.$refs['addForm'].resetFields();
      //           that.addFormVisible = false;
      //           that.search();
      //         } else {
      //           that.$message.error({showClose: true, message: '修改失败', duration: 2000});
      //         }
      //       }, function (err) {
      //         that.loading = false;
      //         that.$message.error({showClose: true, message: err.toString(), duration: 2000});
      //       }).catch(function (error) {
      //         that.loading = false;
      //         console.log(error);
      //         that.$message.error({showClose: true, message: '请求出现异常', duration: 2000});
      //       });

      //     }
      //   });
      // },

      submitUpload(forName) {
              let self = this
                      this.$confirm('此操作将无法撤回, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                      }).then(() => {
                        self.$refs[forName].validate((valid) => {
                          if (valid) {
                            self.loading = true;
                            self.$refs.upload.submit();
                            self.dialogVisible = false;
                            self.addFormVisible = false;
                            self.search();
                            self.loading = false

                          } else {
                            return false
                          }
                        })
                      }).catch(() => {
                        this.$message({
                          type: 'info',
                          message: '已取消更新'
                        })
                      })
                      this.loading = false;
            },

      //批量删除
      batchDeleteBook: function () {
        let ids = this.sels.map(item => item.id).toString();
        let that = this;
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          that.loading = true;
          API.removeBatch(ids).then(function (result) {
            that.loading = false;
            if (result && parseInt(result.errcode) === 0) {
              that.$message.success({showClose: true, message: '删除成功', duration: 1500});
              that.search();
            }
          }, function (err) {
            that.loading = false;
            that.$message.error({showClose: true, message: err.toString(), duration: 2000});
          }).catch(function (error) {
            that.loading = false;
            console.log(error);
            that.$message.error({showClose: true, message: '请求出现异常', duration: 2000});
          });
        }).catch(() => {

        });
      }
    },
    mounted() {
      this.handleSearch()
    }
  }
</script>

<style>
  .demo-table-expand label {
    font-weight: bold;
  }
</style>
